package com.spring.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bean.Message;
import com.spring.controller.dto.RedisDTO;
import com.spring.controller.service.JedisServiceRemote;
import com.spring.controller.util.ObjectUtil;

@SuppressWarnings("rawtypes")
@Controller
public class RedisController extends BaseController {
	
	@Autowired
    private JedisServiceRemote jedisServiceRemote;
	
	
	@RequestMapping
	@ResponseBody
	public ApiModel testSetRedis() {
		String sessionId = "1234567890";
		RedisDTO session = new RedisDTO();
		session.setNickname("huangyaoming");
		session.setYzt(sessionId);
		jedisServiceRemote.setObject("USER_SESSION_" + sessionId, session, 3600);
		return buildSuccMsg("success!");
	}
	
	@RequestMapping
	@ResponseBody
	public ApiModel testGetRedis() {
		try {
			String sessionId = "1234567890";
			RedisDTO result = jedisServiceRemote.getObject("USER_SESSION_" + sessionId, new RedisDTO());
			if(result == null){
				logger.info("The value of result is : " + result);
				return buildErrorMsg(null, "-1", "对不起，该SESSION已经失效，请重新登录！");
			}
			logger.info("++++++++++++++++++++++++++++++++++++++++++" + result.getNickname());
			logger.info("++++++++++++++++++++++++++++++++++++++++++" + result.getYzt());
			return buildSuccMsg(result);
		} catch (Exception e) {
			return buildErrorMsg(null, "-2", e.getMessage());
		}
		
	}
	
	@RequestMapping
	@ResponseBody
	public ApiModel testRedisQuene(){
		try {
			byte[] redisKey = "key".getBytes();
			Message msg1 = new Message(1, "内容1");
			jedisServiceRemote.lpush(redisKey, ObjectUtil.objectToBytes(msg1));
			Message msg2 = new Message(2, "内容2");
			jedisServiceRemote.lpush(redisKey, ObjectUtil.objectToBytes(msg2));
			Message msg3 = new Message(3, "内容3");
			jedisServiceRemote.lpush(redisKey, ObjectUtil.objectToBytes(msg3));
			 
			byte[] bytes = jedisServiceRemote.rpop(redisKey);
	        Message msg = (Message) ObjectUtil.bytesToObject(bytes);
	        if(msg != null){
	            System.out.println(msg.getId()+"   "+msg.getContent());
	        }
			
			return buildSuccMsg(null);
		} catch (Exception e) {
			return buildErrorMsg(null, "-2", e.getMessage());
		}
	}
	
}
